package vcsn.entities;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.Vector;

import vcsn.Config;

public class PeerList {
	public PeerList(){
		
	}
	
	public boolean comparePeerList(Vector<String> peerListOne, Vector<String> peerListTwo){
		boolean result = false;
		
		for (String lEntry : peerListTwo){
			// Insert the Peer if it is not present in One.
			if (!peerListOne.contains(lEntry)){
				result = true;
			}
		}
		
		for (String lEntry : peerListOne){
			// Insert the Peer if it is not present in One.
			if (!peerListTwo.contains(lEntry)){
				result = true;
			}
		}
		
		return result;
		
	}
	
	public Vector<String> mergePeerList(Vector<String> peerListOne, Vector<String> peerListTwo){
		Vector<String> result = new Vector<String>();
		// Go over all elements in peer list One, put them in the new peer list.
		for (String lEntry : peerListOne){
			result.add(lEntry);
		}

		// Go over all elements in peer list Two,
		for (String lEntry : peerListTwo){
			// Insert the Peer if it is not present in One.
			if (!result.contains(lEntry)){
				result.add(lEntry);
			}
		}

		// Return the merged peer list.
		return result;
	}
	
	public Vector<String> getPeerList(String peerListFilePath){
		File configFile = new File(peerListFilePath);
		if(!configFile.exists()){
			return new Vector<String>();
		}
		try{
			Scanner scn = new Scanner(configFile);
			Vector<String> peerList = new Vector<String>();
			while(scn.hasNextLine()){
				String peerStr = scn.nextLine();
				if(!peerStr.isEmpty()){
					peerList.add(peerStr);
				}
			}
			scn.close();
			return peerList;
		}catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean updateLocalPeerList(String peerListFilePath, Vector<String> peerList){
		File peerFile = new File(peerListFilePath);
		try {
			if(!peerFile.exists()){
				peerFile.createNewFile();
			}
			FileWriter fWriter = new FileWriter(peerFile, false);
			if(peerList.size() <= 0){
				fWriter.write("");
			}else{
				for(int i = 0; i < peerList.size(); i++){
					if(i + 1 < peerList.size()){
						fWriter.write(peerList.get(i) + "\n");
					}else{
						fWriter.write(peerList.get(i));
					}
				}
			}
			fWriter.flush();
			fWriter.close();
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
			return false;
		}
	}
}
